package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.*;
import com.itheima.dto.OrdersDto;
import com.itheima.service.AddressBookService;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import com.itheima.service.ShoppingCartService;
import com.itheima.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@RequestMapping("/order")
@RestController
public class OrderController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders){
        log.info("orderss:{}",orders);

        boolean flag = ordersService.submit(orders);

        return flag?R.success("下单成功！"):R.error("下单失败！");
    }




    //更改派送状态
    @PutMapping
    R put(@RequestBody Orders orders){

        Long id = orders.getId();
        Integer status = orders.getStatus();
        Orders one = ordersService.getById(id);
        if (one!=null){
            one.setStatus(status);
        }
        boolean flag = ordersService.updateById(one);
        return flag?R.success("修改成功"):R.error("修改失败");
    }
    //订单分页查询
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String number, String beginTime,String endTime){
        //String类型参数beginTime 转 Date类型
        Date begin=null;
        Date end=null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (begin != null && end != null) {
            try {
                begin = dateFormat.parse(beginTime);
                end = dateFormat.parse(endTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //1.创建Page对象 设置分页参数【当前页码 每页显示条数】
        Page<Orders> ordersPage=new Page<>(page,pageSize);

        //2.设置查询条件 【订单编号 number 下单时间 orderTime】
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();

        wrapper.like(number!=null,Orders::getNumber,number).between(beginTime!=null,Orders::getOrderTime,beginTime,endTime).orderByDesc(Orders::getOrderTime);

        //3.调用service完成分页查询，返回分页数据
        ordersService.page(ordersPage,wrapper);

        return R.success(ordersPage);
    }


    /**
     * 历史订单查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R userPage(int page ,int pageSize){
        Page<Orders> ordersPage = new Page<>(page, pageSize);

        Long userId = BaseContext.getCurrentId();

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,userId).orderByDesc(Orders::getOrderTime);

        ordersService.page(ordersPage, wrapper);

        List<Orders> ordersList = ordersPage.getRecords();

        Page<OrdersDto> ordersDtoPage = new Page<>();
        List<OrdersDto> ordersDtolist =new ArrayList<>();

        for (Orders orders : ordersList) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders,ordersDto);

            Long ordersId = orders.getId();
            LambdaQueryWrapper<OrderDetail> detailWrapper = new LambdaQueryWrapper<>();
            detailWrapper.eq(OrderDetail::getOrderId,ordersId);
            List<OrderDetail> orderDetailList = orderDetailService.list(detailWrapper);
            for (OrderDetail orderDetail : orderDetailList) {
                if (orderDetail.getDishFlavor()!=null){
                    orderDetail.setName(orderDetail.getName()+"---"+orderDetail.getDishFlavor());}

            }
            ordersDto.setOrderDetails(orderDetailList);

            ordersDto.setAddress(orders.getAddress());
            ordersDto.setPhone(orders.getPhone());
            ordersDto.setConsignee(orders.getConsignee());
            ordersDtolist.add(ordersDto);
        }



        ordersDtoPage.setRecords(ordersDtolist);
        ordersDtoPage.setTotal(ordersPage.getTotal());


        return R.success(ordersDtoPage);

    }
}

